//
//  SEPrescriptionPickDrugsDetailView.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/5/11.
//

import UIKit

class SEPrescriptionPickDrugsDetailView: UIView {
    
    var viewModel = SEPrescriptionDrugPickViewModel() {
        didSet { tableView.reloadData() }
    }
    
    var backHandler: (() -> Void)?
    var confirmHandler: (() -> Void)?
    var selectedHandler: ((SEPrescriptionPickDrugsDetailCellType) -> Void)?

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.delegate = self
            tableView.dataSource = self
            tableView.backgroundColor = .white
            tableView.tableFooterView = UIView()
            
            tableView.register(SEPrescriptionPickDrugsDetailCell.nibForCell(),
                               forCellReuseIdentifier: SEPrescriptionPickDrugsDetailCell.reuseIdentifier())
            tableView.register(SEPrescriptionPickDrugsDetailButtonCell.nibForCell(),
                               forCellReuseIdentifier: SEPrescriptionPickDrugsDetailButtonCell.reuseIdentifier())
        }
    }
    
    @IBAction private func backAction() {
        backHandler?()
    }
}

extension SEPrescriptionPickDrugsDetailView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellType = SEPrescriptionPickDrugsDetailCellType(rawValue: indexPath.row) ?? .confirm
        
        switch cellType {
        case .confirm:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionPickDrugsDetailButtonCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionPickDrugsDetailButtonCell
            cell.confirmHandler = confirmHandler
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionPickDrugsDetailCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionPickDrugsDetailCell
            cell.update(with: viewModel, cellType: cellType)
            return cell
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let cellType = SEPrescriptionPickDrugsDetailCellType(rawValue: indexPath.row) ?? .drugName
        selectedHandler?(cellType)
    }
}
